import cgi
import wsgiref.handlers
import os
import logging
import datetime

from google.appengine.ext.webapp import template

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp

#from string import strip, rstrip, lstrip, replace
import re
from google.appengine.api import mail
from google.appengine.api import urlfetch


from google.appengine.api.labs import taskqueue

def strip_tags(value):
  "Return the given HTML with all tags stripped."
  return re.sub(r'<[^>]*?>', '', value) 

def require_admin(handler_method):
  """Decorator that requires the requesting user to be an admin."""
  def decorate(myself, *args, **kwargs):
    if ('HTTP_X_APPENGINE_TASKNAME' in os.environ
        or users.is_current_user_admin()):
      handler_method(myself, *args, **kwargs)
    elif users.get_current_user() is None:
      myself.redirect(users.create_login_url(myself.request.url))
    else:
      myself.response.set_status(401)
  return decorate


################################################################################
# Send emails

class MailHandler(webapp.RequestHandler):
  def get(self):
    user = users.get_current_user()
    if not user:
      self.redirect(users.create_login_url(self.request.path))
      return
    self.response.out.write(
        template.render('mail.html', {
            'email': user.email()
        }))

  def post(self):
    campaign = self.request.get('campaign')
    urlto = self.request.get('tourl')
    resultto = urlfetch.fetch(urlto)
    for line in resultto.content.splitlines():
      for email in line.split(","):
        if email:
          mailqueue = MailQueue2()
          mailqueue.campaign = campaign
          mailqueue.email = email
          mailqueue.put()
	   
    taskqueue.add(
        url='/worker/email',
        #url='/worker/email?to=fedex1@gmail.com',
        #method='GET')
        #params={'from': 'checkout@brooklyncoop.org', 'to': users.get_current_user().email()})
	params={ 'campaign': self.request.get('campaign'), 'from': self.request.get('from'), 'to': self.request.get('to'), 'bodyurl': self.request.get('bodyurl'), 'tourl': self.request.get('tourl')})
    self.redirect('/mail')


class MailWorker(webapp.RequestHandler):
  # @require_admin
  def post(self):
    # logging.debug("XXX task send mail 1")
    # mail.send_mail( 'fedex1@gmail.com', self.request.get('to'), 'A special message to you', 'This is a test of the task queue')
    # url = 'http://wsxnyc.org/letter_checkout.html'
    url = self.request.get('bodyurl')
    logging.debug("URL: %s" % url)
    if url:
      resultfetch = urlfetch.fetch(url)
    # mail.send_mail( self.request.get('from'), self.request.get('to'), 'A special message to you', 'This is a test of the task queue')
    q = db.GqlQuery('SELECT * FROM MailQueue2 WHERE campaign = :1 ORDER BY sent ASC LIMIT 1', self.request.get('campaign'))
    if q: 
      results = q.fetch(1)
      for result in results:
	logging.debug("XXX task send mail TO: %s" % result.email)
        if not result.sent:
          mail.send_mail(sender=self.request.get('from'),
    	              # to=self.request.get('to'),
    	              to=result.email,
    		      bcc="fedex1@gmail.com",
    		      #subject="An order has been processed: %s" % result.shopping_cart_items_item_1_item_description ,
		      subject="Simple Online Event Registration for Race Directors",
    		      html=resultfetch.content,
  				                  body="""
Simple Online Event Registration

Details: 
%s
""" % url)
    # logging.debug("XXX task send mail 2")
          result.sent = datetime.datetime.today()
	  result.put()

          taskqueue.add(
            url='/worker/email',
            #url='/worker/email?to=fedex1@gmail.com',
            #method='GET')
            #params={'from': 'checkout@brooklyncoop.org', 'to': users.get_current_user().email()})
    	    params={ 'campaign': self.request.get('campaign'), 'from': self.request.get('from'), 'to': self.request.get('to'), 'bodyurl': self.request.get('bodyurl'), 'tourl': self.request.get('tourl')})

  # @require_admin
  def get(self):
    logging.debug("task send mail 1")
    # mail.send_mail( 'fedex1@gmail.com', self.request.get('to'), 'A special message to you', 'This is a test of the task queue')
    logging.debug("task send mail 2")

################################################################################

class MailQueue2(db.Model):
  campaign = db.StringProperty()
  email = db.StringProperty()
  first = db.StringProperty()
  last = db.StringProperty()
  comments = db.TextProperty()
  sent = db.DateTimeProperty()
  created = db.DateTimeProperty(auto_now_add=True)
  modified = db.DateTimeProperty(auto_now=True)

class Greeting(db.Model):
	author = db.UserProperty()
	first = db.StringProperty(multiline=False)
	last = db.StringProperty(multiline=False)
	age = db.IntegerProperty(default = 0)
	gender = db.StringProperty(multiline=False)
	division = db.StringProperty(multiline=False)
	date = db.DateTimeProperty(auto_now_add=True)

class CheckoutLog(db.Model):
	uri = db.StringProperty()
	_type = db.StringProperty() 
	buyer_billing_address_address1 = db.StringProperty() 
	buyer_billing_address_address2 = db.StringProperty() 
	buyer_billing_address_city = db.StringProperty() 
	buyer_billing_address_company_name = db.StringProperty() 
	buyer_billing_address_contact_name = db.StringProperty() 
	buyer_billing_address_country_code = db.StringProperty() 
	buyer_billing_address_email = db.StringProperty() 
	buyer_billing_address_fax = db.StringProperty() 
	buyer_billing_address_phone = db.StringProperty() 
	buyer_billing_address_postal_code = db.StringProperty() 
	buyer_billing_address_region = db.StringProperty() 
	buyer_id = db.StringProperty() 
	buyer_marketing_preferences_email_allowed = db.StringProperty() 
	buyer_shipping_address_address1 = db.StringProperty() 
	buyer_shipping_address_address2 = db.StringProperty() 
	buyer_shipping_address_city = db.StringProperty() 
	buyer_shipping_address_company_name = db.StringProperty() 
	buyer_shipping_address_contact_name = db.StringProperty() 
	buyer_shipping_address_country_code = db.StringProperty() 
	buyer_shipping_address_email = db.StringProperty() 
	buyer_shipping_address_fax = db.StringProperty() 
	buyer_shipping_address_phone = db.StringProperty() 
	buyer_shipping_address_postal_code = db.StringProperty() 
	buyer_shipping_address_region = db.StringProperty() 
	financial_order_state = db.StringProperty() 
	fulfillment_order_state = db.StringProperty() 
	google_order_number = db.StringProperty() 
	latest_charge_amount = db.StringProperty() 
	latest_charge_amount_currency = db.StringProperty() 
	new_financial_order_state = db.StringProperty() 
	new_fulfillment_order_state = db.StringProperty() 
	order_adjustment_adjustment_total = db.StringProperty() 
	order_adjustment_adjustment_total_currency = db.StringProperty() 
	order_adjustment_total_tax = db.StringProperty() 
	order_adjustment_total_tax_currency = db.StringProperty() 
	order_total = db.StringProperty() 
	order_total_currency = db.StringProperty() 
	previous_financial_order_state = db.StringProperty() 
	previous_fulfillment_order_state = db.StringProperty() 
	risk_information_avs_response = db.StringProperty() 
	risk_information_billing_address_address1 = db.StringProperty() 
	risk_information_billing_address_address2 = db.StringProperty() 
	risk_information_billing_address_city = db.StringProperty() 
	risk_information_billing_address_company_name = db.StringProperty() 
	risk_information_billing_address_contact_name = db.StringProperty() 
	risk_information_billing_address_country_code = db.StringProperty() 
	risk_information_billing_address_email = db.StringProperty() 
	risk_information_billing_address_fax = db.StringProperty() 
	risk_information_billing_address_phone = db.StringProperty() 
	risk_information_billing_address_postal_code = db.StringProperty() 
	risk_information_billing_address_region = db.StringProperty() 
	risk_information_buyer_account_age = db.StringProperty() 
	risk_information_cvn_response = db.StringProperty() 
	risk_information_eligible_for_protection = db.StringProperty() 
	risk_information_ip_address = db.StringProperty() 
	risk_information_partial_cc_number = db.StringProperty() 
	shopping_cart_items = db.StringProperty() 
	shopping_cart_items_item_1_digital_content_description = db.StringProperty() 
	shopping_cart_items_item_1_item_description = db.StringProperty() 
	shopping_cart_items_item_1_item_name = db.StringProperty() 
	shopping_cart_items_item_1_quantity = db.StringProperty() 
	shopping_cart_items_item_1_unit_price = db.StringProperty() 
	shopping_cart_items_item_1_unit_price_currency = db.StringProperty() 
	timestamp = db.StringProperty() 
	total_charge_amount = db.StringProperty() 
	total_charge_amount_currency = db.StringProperty() 
	body = db.StringProperty()
	arguments = db.StringProperty()
	values = db.StringProperty()
	html = db.TextProperty()

class DumpTest(webapp.RequestHandler):
  def get(self):
    self.response.out.write('<html><body>')
    count = 0
    #entities = CheckoutLog.all().filter('_type =', 'order-state-change-notification').fetch(100)
    entities = CheckoutLog.all().fetch(100)
    while entities:
      for entity in entities:
        # Do something with entity
	count += 1
        self.response.out.write(entity._type)
        self.response.out.write(' - ')
        self.response.out.write(entity.key())
        self.response.out.write(' - ')
        self.response.out.write(entity.timestamp)
        self.response.out.write('<br/>')
      #entities = CheckoutLog.all().filter('_type =', 'order-state-change-notification').filter('__key__ >', entities[-1].key()).fetch(100)
      entities = CheckoutLog.all().filter('__key__ >', entities[-1].key()).fetch(100)
    self.response.out.write('count: %s<br/>' % count)
    self.response.out.write('</body></html>')


class Guestbook(webapp.RequestHandler):
  def post(self):
    greeting = Greeting()

    if users.get_current_user():
      greeting.author = users.get_current_user()

    greeting.first = self.request.get('first')
    greeting.last = self.request.get('last')
    greeting.age = int(self.request.get('age'))
    greeting.gender = self.request.get('gender')
    greeting.division = self.request.get('division')
    greeting.put()
    self.redirect('/')

class SendCheckout(webapp.RequestHandler):
  def get(self):
    urlto = 'http://wsxnyc.org/to_checkout.txt'
    resultto = urlfetch.fetch(urlto)

    url = 'http://wsxnyc.org/letter_checkout.html'
    resultfetch = urlfetch.fetch(url)

    for line in resultto.content.splitlines():
      for email in line.split(","):
        mail.send_mail(sender="checkout@brooklyncoop.org",
    	              to=email,
    	              #to=toaddress,
    		      bcc="fedex1@gmail.com",
    		      #subject="An order has been processed: %s" % result.shopping_cart_items_item_1_item_description ,
		      subject="Simple Online Event Registration for Race Directors",
    		      html=resultfetch.content,
  				                  body="""
Simple Online Event Registration

Details: 
%s
""" % url)
      
    path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, {}))

class Send(webapp.RequestHandler):
  def get(self):
    #urlto = 'http://wsxnyc.org/to2.txt'
    urlto = 'http://wsxnyc.org/to15.txt'
    resultto = urlfetch.fetch(urlto)

    url = 'http://wsxnyc.org/letter.html'
    resultfetch = urlfetch.fetch(url)

    for line in resultto.content.splitlines():
      for email in line.split(","):
	if len(email) > 0:
          mail.send_mail(sender="nyrrc-democracy-now@brooklyncoop.org",
    	              #to="fedex1@gmail.com",
    	              to=email,
    	              #to=toaddress,
    		      bcc="fedex1@gmail.com",
    		      #subject="A letter test: %s" % email ,
		      subject="A letter for NYRRC long time member: %s" % email,
    		      html=resultfetch.content,
  				                  body="""
A letter for NYRRC long time members

Details: 
%s
""" % url)
      

#     mail.send_mail(sender="nyrrc-democracy-now@brooklyncoop.org",
# 	              to="fedex1@gmail.com",
# 	              #to=toaddress,
# 		      bcc="fedex1@gmail.com",
# 		      #subject="An order has been processed: %s" % result.shopping_cart_items_item_1_item_description ,
# 		      subject="A letter for NYRRC long time members",
# 		      html=resultfetch.content,
# 				                  body="""
# A letter for NYRRC long time members
# 
# Details: 
# %s
# """ % url)


    path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, {}))

class List(webapp.RequestHandler):
  @require_admin
  def get(self):
    #self.response.out.write(self.request.get('google_order_number'))
    #self.response.out.write('<br/>')
    self.response.out.write('<html><body>')
    if self.request.get('google_order_number'):
      q = db.GqlQuery('SELECT * FROM CheckoutLog WHERE google_order_number = :1 ORDER BY timestamp desc' , self.request.get('google_order_number'))
      #q = db.GqlQuery("SELECT * FROM CheckoutLog where google_order_number = ':1' order by timestamp desc" , self.request.get('google_order_number'))
      #q = db.GqlQuery("SELECT * FROM CheckoutLog WHERE google_order_number = '757965836430932' order by timestamp desc" )
    elif self.request.get('new'):
	q = db.GqlQuery('SELECT * FROM CheckoutLog WHERE _type = :1 order by timestamp desc limit 500', 'new-order-notification')
    else:
      q = db.GqlQuery('SELECT * FROM CheckoutLog order by timestamp desc limit 100')
    if q: 
      results = q.fetch(100)
      for result in results:
        self.response.out.write('<b><a href="/list?google_order_number=')
        self.response.out.write(result.google_order_number)
        self.response.out.write('">')
        self.response.out.write(result.google_order_number)
        self.response.out.write('</a></b>')
        self.response.out.write(' , ')
        self.response.out.write(result.timestamp)
        self.response.out.write(' , ')
        self.response.out.write(result._type)
        self.response.out.write(' , ')
        self.response.out.write(result.new_financial_order_state)
        self.response.out.write(' , ')
        self.response.out.write(result.new_fulfillment_order_state)
        self.response.out.write(' , ')
        self.response.out.write(result.latest_charge_amount)
        self.response.out.write(' , ')
        self.response.out.write(result.latest_charge_amount_currency)
        self.response.out.write(' , ')
        self.response.out.write(result.buyer_shipping_address_contact_name)
        self.response.out.write(' , ')
        self.response.out.write(result.buyer_shipping_address_address1)
        self.response.out.write(' , ')
        self.response.out.write(result.buyer_shipping_address_address2)
        self.response.out.write(' , ')
        self.response.out.write(result.buyer_billing_address_city)
        self.response.out.write(' , ')
        self.response.out.write(result.buyer_billing_address_postal_code)
        self.response.out.write(' , ')
        self.response.out.write(result.buyer_billing_address_email)
        self.response.out.write(' , ')
        self.response.out.write(result.buyer_billing_address_region)
        self.response.out.write(' , ')
        self.response.out.write(result.shopping_cart_items_item_1_item_name)
        self.response.out.write(' , ')
        self.response.out.write(result.shopping_cart_items_item_1_item_description)
        self.response.out.write(' , ')
        self.response.out.write(result.shopping_cart_items_item_1_digital_content_description)
        self.response.out.write(' , ')


	if result.shopping_cart_items_item_1_digital_content_description:
          url = 'url'
          url = 'http://move.brooklynmarathon.com/showXXXentry/%s' % re.sub("^.*-","",result.shopping_cart_items_item_1_digital_content_description)
          eventtype = strip_tags(re.sub("-.*$","",re.sub("^.* tracking: ","",result.shopping_cart_items_item_1_digital_content_description)))
          url = re.sub("XXX",eventtype,url)
	  # self.response.out.write('<a href="http://move.brooklynmarathon.com/showclubentry/%s">Details</a>' % re.sub("^.*-","",result.shopping_cart_items_item_1_digital_content_description))
	  self.response.out.write('<a href="%s">Details</a>' % url)
        if self.request.get('html'):
	  if result.html:
            self.response.out.write(' , ')
	    self.response.out.write('<br/>%s<hr/>' % result.html)


	#self.response.out.write('XX%sYY' % re.sub("^.*-","",result.shopping_cart_items_item_1_digital_content_description))
        #self.response.out.write(' , ')
        #self.response.out.write(result.entity)
        self.response.out.write('<br/>')

        if self.request.get('debug'):
          for attr, value in result.__dict__.iteritems():
            self.response.out.write(attr)
            self.response.out.write(' = ')
            self.response.out.write(value)
            self.response.out.write('<br/>')
          self.response.out.write('<hr/>')
    self.response.out.write('</body></html>')


class MainPage(webapp.RequestHandler):
  def get(self):
     self.redirect('/list')
#     q = db.GqlQuery("SELECT * FROM CheckoutLog WHERE google_order_number = :1 and shopping_cart_items_item_1_digital_content_description != '' limit 1" , self.request.get('google_order_number'))
#     results = q.fetch(1)
#     checkoutlog = CheckoutLog()
#     checkoutlog.uri = self.request.uri
#     checkoutlog.body = self.request.body
#     checkoutlog.arguments = "&".join(map(str, self.request.arguments()))
#     checkoutlog.new_fulfillment_order_state = self.request.get('new_fulfillment-order-state')
# #    listx = []
# #    for x in self.request.arguments():
# #      list.append(x) 
# #    checkoutlog.values = "&".join(map(str, list))
#     checkoutlog.put()
# 
#     if checkoutlog.new_fulfillment_order_state == 'DELIVERED':
#       mail.send_mail(sender="checkout@brooklyncoop.org",
# 	              to="fedex1@gmail.com",
# 		      subject="An order has been processed",
# 				                  body="""
# Order has been processed
# 
# Details: 
# %s
# """ % 'xxx')
#     path = os.path.join(os.path.dirname(__file__), 'index.html')
#     self.response.out.write(template.render(path, {}))


  #  @require_admin  # DOES NOT WORK but needed
  def post(self):
    checkoutlog = CheckoutLog()
    checkoutlog.uri = self.request.uri
    checkoutlog._type = self.request.get('_type')
    checkoutlog.buyer_billing_address_address1 = self.request.get('buyer-billing-address.address1')
    checkoutlog.buyer_billing_address_address2 = self.request.get('buyer-billing-address.address2')
    checkoutlog.buyer_billing_address_city = self.request.get('buyer-billing-address.city')
    checkoutlog.buyer_billing_address_company_name = self.request.get('buyer-billing-address.company-name')
    checkoutlog.buyer_billing_address_contact_name = self.request.get('buyer-billing-address.contact-name')
    checkoutlog.buyer_billing_address_country_code = self.request.get('buyer-billing-address.country-code')
    checkoutlog.buyer_billing_address_email = self.request.get('buyer-billing-address.email')
    checkoutlog.buyer_billing_address_fax = self.request.get('buyer-billing-address.fax')
    checkoutlog.buyer_billing_address_phone = self.request.get('buyer-billing-address.phone')
    checkoutlog.buyer_billing_address_postal_code = self.request.get('buyer-billing-address.postal-code')
    checkoutlog.buyer_billing_address_region = self.request.get('buyer-billing-address.region')
    checkoutlog.buyer_id = self.request.get('buyer-id')
    checkoutlog.buyer_marketing_preferences_email_allowed = self.request.get('buyer-marketing-preferences.email-allowed')
    checkoutlog.buyer_shipping_address_address1 = self.request.get('buyer-shipping-address.address1') 
    checkoutlog.buyer_shipping_address_address2 = self.request.get('buyer-shipping-address.address2')
    checkoutlog.buyer_shipping_address_city = self.request.get('buyer-shipping-address.city')
    checkoutlog.buyer_shipping_address_company_name = self.request.get('buyer-shipping-address.company-name')
    checkoutlog.buyer_shipping_address_contact_name = self.request.get('buyer-shipping-address.contact-name')
    checkoutlog.buyer_shipping_address_country_code = self.request.get('buyer-shipping-address.country-code')
    checkoutlog.buyer_shipping_address_email = self.request.get('buyer-shipping-address.email')
    checkoutlog.buyer_shipping_address_fax = self.request.get('buyer-shipping-address.fax')
    checkoutlog.buyer_shipping_address_phone = self.request.get('buyer-shipping-address.phone')
    checkoutlog.buyer_shipping_address_postal_code = self.request.get('buyer-shipping-address.postal-code')
    checkoutlog.buyer_shipping_address_region = self.request.get('buyer-shipping-address.region')
    # checkoutlog.financial_order_state = self.request.get('financial-order-state')
    checkoutlog.fulfillment_order_state = self.request.get('fulfillment-order-state')
    checkoutlog.google_order_number = self.request.get('google-order-number')
    checkoutlog.latest_charge_amount = self.request.get('latest-charge-amount')
    checkoutlog.latest_charge_amount_currency = self.request.get('latest-charge-amount.currency')
    checkoutlog.new_financial_order_state = self.request.get('new-financial-order-state')
    checkoutlog.new_fulfillment_order_state = self.request.get('new-fulfillment-order-state')
    checkoutlog.order_adjustment_adjustment_total = self.request.get('order-adjustment.adjustment-total')
    checkoutlog.order_adjustment_adjustment_total_currency = self.request.get('order-adjustment.adjustment-total.currency')
    checkoutlog.order_adjustment_total_tax = self.request.get('order-adjustment.total-tax')
    checkoutlog.order_adjustment_total_tax_currency = self.request.get('order-adjustment.total-tax.currency')
    checkoutlog.order_total = self.request.get('order-total')
    checkoutlog.order_total_currency = self.request.get('order-total.currency')
    checkoutlog.previous_financial_order_state = self.request.get('previous-financial-order-state')
    checkoutlog.previous_fulfillment_order_state = self.request.get('previous-fulfillment-order-state')
    checkoutlog.risk_information_avs_response = self.request.get('risk-information.avs-response')
    checkoutlog.risk_information_billing_address_address1 = self.request.get('risk-information.billing-address.address1')
    checkoutlog.risk_information_billing_address_address2 = self.request.get('risk-information.billing-address.address2')
    checkoutlog.risk_information_billing_address_city = self.request.get('risk-information.billing-address.city')
    checkoutlog.risk_information_billing_address_company_name = self.request.get('risk-information.billing-address.company-name')
    checkoutlog.risk_information_billing_address_contact_name = self.request.get('risk-information.billing-address.contact-name')
    checkoutlog.risk_information_billing_address_country_code = self.request.get('risk-information.billing-address.country-code')
    checkoutlog.risk_information_billing_address_email = self.request.get('risk-information.billing-address.email')
    checkoutlog.risk_information_billing_address_fax = self.request.get('risk-information.billing-address.fax')
    checkoutlog.risk_information_billing_address_phone = self.request.get('risk-information.billing-address.phone')
    checkoutlog.risk_information_billing_address_postal_code = self.request.get('risk-information.billing-address.postal-code')
    checkoutlog.risk_information_billing_address_region = self.request.get('risk-information.billing-address.region')
    checkoutlog.risk_information_buyer_account_age = self.request.get('risk-information.buyer-account-age')
    checkoutlog.risk_information_cvn_response = self.request.get('risk-information.cvn-response')
    checkoutlog.risk_information_eligible_for_protection = self.request.get('risk-information.eligible-for-protection')
    checkoutlog.risk_information_ip_address = self.request.get('risk-information.ip-address')
    checkoutlog.risk_information_partial_cc_number = self.request.get('risk-information.partial-cc-number')
    checkoutlog.shopping_cart_items = self.request.get('shopping-cart.items')
    checkoutlog.shopping_cart_items_item_1_digital_content_description = self.request.get('shopping-cart.items.item-1.digital-content.description')
    checkoutlog.shopping_cart_items_item_1_item_description = self.request.get('shopping-cart.items.item-1.item-description')
    checkoutlog.shopping_cart_items_item_1_item_name = self.request.get('shopping-cart.items.item-1.item-name')
    checkoutlog.shopping_cart_items_item_1_quantity = self.request.get('shopping-cart.items.item-1.quantity')
    checkoutlog.shopping_cart_items_item_1_unit_price = self.request.get('shopping-cart.items.item-1.unit-price')
    checkoutlog.shopping_cart_items_item_1_unit_price_currency = self.request.get('shopping-cart.items.item-1.unit-price.currency')
    checkoutlog.timestamp = self.request.get('timestamp')
    checkoutlog.total_charge_amount = self.request.get('total-charge-amount')
    checkoutlog.total_charge_amount_currency = self.request.get('total-charge-amount.currency')

    checkoutlog.put()
    q = db.GqlQuery('SELECT * FROM CheckoutLog WHERE google_order_number = :1 and shopping_cart_items_item_1_digital_content_description != :2 limit 1' , checkoutlog.google_order_number, '')
    results = q.fetch(1)

    
    url = 'url'
    url1 = 'url'
    toaddress = 'toaddress'
    save_result = None
    for result in results:
      url = 'http://move.brooklynmarathon.com/showXXXentry/%s' % re.sub("^.*-","",result.shopping_cart_items_item_1_digital_content_description)
      url1 = 'http://move.brooklynmarathon.com/checkoutXXXentry/%s/%s' % (re.sub("^.*-","",result.shopping_cart_items_item_1_digital_content_description), result.google_order_number)
      toaddress = strip_tags(re.sub(" tracking:.*$","",re.sub("^.* contact: ","",result.shopping_cart_items_item_1_digital_content_description)))
      eventtype = strip_tags(re.sub("-.*$","",re.sub("^.* tracking: ","",result.shopping_cart_items_item_1_digital_content_description)))
      save_result = result

    url = re.sub("XXX",eventtype,url)
    url1 = re.sub("XXX",eventtype,url1)

    resultfetch = urlfetch.fetch(url)
    save_result.html = resultfetch.content
    save_result.put()

    #if eventtype == 'event':
    # only do this when item is delivered
    #logging.debug("111 delivered test order state: %s" % checkoutlog.new_fulfillment_order_state)
    #logging.debug("111 delivered test: %s" % url1)
    #resultfetch = urlfetch.fetch(url1)


    listx = []
    listx.append(result.shopping_cart_items_item_1_item_name) 
    listx.append(result.shopping_cart_items_item_1_item_description) 
    listx.append(result.order_total) 
    listx.append(result.shopping_cart_items_item_1_unit_price_currency) 
    listx.append(checkoutlog.google_order_number) 
    liststr = "|".join(map(str, listx))

    if checkoutlog.new_fulfillment_order_state == 'DELIVERED':
      resultfetch = urlfetch.fetch(url1)
      #logging.debug("222 delivered test: %s" % url1)
      #mail.send_mail(sender="fedex1@gmail.com",
      #mail.send_mail(sender='BrooklynCoop Checkout <checkout@brooklyncoop.org>',
      #mail.send_mail(sender='"BrooklynCoop Checkout" <checkout@brooklyncoop.org>',
      mail.send_mail(sender="checkout@brooklyncoop.org",
	              #to="fedex1@gmail.com",
	              to=toaddress,
		      bcc="fedex1@gmail.com",
		      #subject="An order has been processed: %s" % result.shopping_cart_items_item_1_item_description ,
		      subject="An order has been processed: %s" % liststr,
		      html=resultfetch.content,
				                  body="""
Order has been processed

Details: 
%s
""" % url)
#""" % resultfetch.content)
# """ % checkoutlog.google_order_number)

    # email to checkoutlog.shopping_cart_items_item_1_digital_content_description
    # checkoutlog.shopping_cart_items_item_1_digital_content_description format is email: xxx  tracking: club-clubid-clubentryid
    # update move.brooklynmarathon club to delivered state

    path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, {}))


class MainPage1(webapp.RequestHandler):
  def get(self):
    greetings_query = Greeting.all().order('-date')
    greetings = greetings_query.fetch(10)

    if users.get_current_user():
      url = users.create_logout_url(self.request.uri)
      url_linktext = 'Logout'
    else:
      url = users.create_login_url(self.request.uri)
      url_linktext = 'Login'

    template_values = {
      'greetings': greetings,
      'url': url,
      'url_linktext': url_linktext,
      }

    path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, template_values))

  def post(self):
    print self.request


def main():
  application = webapp.WSGIApplication(
                                       [
					   ('/', MainPage),
					   ('/list', List),
					   ('/send', Send),
					   ('/send_checkout', SendCheckout),
					   ('/dumptest', DumpTest),
      (r'/mail', MailHandler),
      (r'/worker/email', MailWorker),
                                        ('/signup', Guestbook)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()


